package com.lzugis.img;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import com.amazonaws.util.json.JSONObject;
import javax.imageio.ImageIO;

public class MergeImg {

    public static File[] getFiles(String path) {
        File file = new File(path);
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            return files;
        } else {
            return null;
        }
    }

    public static void append2File(String file, String content) {
        try {
            File f = new File(file);
            FileWriter fw = new FileWriter(f, true);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();
            fw.flush();
            pw.close();
            fw.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String path = "D:\\lzugis\\code\\lzugis\\out";
        File[] files = getFiles(path + "\\img");
        int width = 32;
        int height = (width + 3) * files.length;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
        bufferedImage = graphics2D.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        graphics2D.dispose();
        graphics2D = bufferedImage.createGraphics();
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if(!file.isDirectory()) {
                String name = file.getName();
                name = name.substring(0, name.lastIndexOf("."));
                BufferedImage bi = ImageIO.read(file);
                int x = 0;
                int y = (width + 3) * i;
                int h = bi.getHeight();
                int w = bi.getWidth();
                graphics2D.drawImage(bi, x, y, w, h, null);
                JSONObject js = new JSONObject();
                js.put("x", x);
                js.put("y", y);
                js.put("width", w);
                js.put("height", h);
                js.put("pixelRatio", 1);
                js.put("visible", "true");
                jsonObject.put(name, js);
            }
        }
        graphics2D.dispose();
        FileOutputStream out = new FileOutputStream(path +"\\sprite.png");
        ImageIO.write(bufferedImage, "PNG", out);
        append2File(path +"\\sprite.json", jsonObject.toString());
    }
}
